package org.dakuo.sgfyController;

import java.io.IOException;

import javax.servlet.http.*;
import javax.servlet.*;


/**
 * Servlet implementation class Login
 */
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		org.dakuo.sgfyModel.SgfyGame g = (org.dakuo.sgfyModel.SgfyGame) request.getSession().getAttribute("game");

		System.out.println(g);
		
		if (request.getParameter("email").isEmpty()
				|| request.getParameter("password").isEmpty()
				|| request.getParameter("host").isEmpty()) {
			request.getSession().setAttribute("game", g);
			RequestDispatcher rd = request.getRequestDispatcher("LoginForm.jsp");
			rd.forward(request, response);
		} else {
			String email = request.getParameter("email");
			String password = request.getParameter("password");
			String host = request.getParameter("host");

			g.setEmail(email);
			g.setPassword(password);
			g.setHostURI(host);

			if (g.login()) {

				request.getSession().setAttribute("game", g);
				RequestDispatcher rd = request.getRequestDispatcher("AutoPlay.jsp");
				rd.forward(request, response);
			} else {
				RequestDispatcher rd = request
						.getRequestDispatcher("LoginForm.jsp");
				rd.forward(request, response);
			}

		}
	}

}
